/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.loopstack.pcc.model;

import java.util.List;
import java.util.concurrent.*;

import org.apache.commons.lang3.tuple.Pair;

import com.google.common.collect.Lists;

/**
 * 
 * @author icanci
 * @since 1.0 Created in 2024/08/02 15:54
 */
public class RunnerPool {
    /** 默认存活时间 */
    private static final Pair<TimeUnit, Long> DEFAULT_KEEP_ALIVE_TIME = Pair.of(TimeUnit.SECONDS, 60L);
    /** 核心线程数 */
    protected static final int                CORE_SIZE               = Runtime.getRuntime().availableProcessors();

    /** 查询线程池 */
    private static final ThreadPoolExecutor   RUNNER_POOL             = new ThreadPoolExecutor(CORE_SIZE,          //
        CORE_SIZE << 1,                                                                                            //
        DEFAULT_KEEP_ALIVE_TIME.getRight(),                                                                        //
        DEFAULT_KEEP_ALIVE_TIME.getKey(),                                                                          //
        new LinkedBlockingQueue<>(2000),                                                                           //
        runnable -> new Thread(runnable, "RunnerPool Biz Pool-" + runnable.hashCode()),                            //
        (r, executor) -> {
            r.run();
        });

    /**
     * 并行处理单元
     * 
     * @param metaCells metaCells
     * @throws ExecutionException ExecutionException
     * @throws InterruptedException InterruptedException
     */
    public void doMetaCellInvoke(List<MetaCell<?, ?, ?>> metaCells) throws ExecutionException, InterruptedException {
        List<FutureTask<Void>> tasks = Lists.newArrayList();
        for (MetaCell<?, ?, ?> metaCell : metaCells) {
            tasks.add(new FutureTask<>(new MetaCellCallable(metaCell)));
        }
        tasks.forEach(RUNNER_POOL::execute);

        for (FutureTask<Void> task : tasks) {
            task.get();
        }
    }

    /**
     * MetaCellCallable
     */
    public static class MetaCellCallable implements Callable<Void> {
        private final MetaCell<?, ?, ?> metaCell;

        public MetaCellCallable(MetaCell<?, ?, ?> metaCell) {
            this.metaCell = metaCell;
        }

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public Void call() throws Exception {
            if (metaCell != null) {
                metaCell.adapter();
            }
            return null;
        }
    }
}
